package netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

/**
 * Netty服务器
 */
public class NettyServer {

    public static final int PORT = 9000;

    public static void main(String[] args) {
        //创建接收客户端的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //创建完成IO通信的线程组
        EventLoopGroup workGroup = new NioEventLoopGroup(10);
        try {
            //创建服务器启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置线程组
            serverBootstrap.group(bossGroup,workGroup)
                    //设置通道的类型
                    .channel(NioServerSocketChannel.class)
                    //设置客户端等待队列的长度
                    .option(ChannelOption.SO_BACKLOG,100)
                    //设置通道的初始化器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //给通道中的管道加处理器
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            //服务器绑定一个端口 sync将异步操作转为同步
            ChannelFuture channelFuture = serverBootstrap.bind(PORT).sync();
            //关闭服务器连接
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭线程组
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}

/**
 * 服务器的输入处理器
 */
class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取操作
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //获得客户端发送的数据
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("收到客户端消息：" + byteBuf.toString(CharsetUtil.UTF_8));
    }

    /**
     * 读取完毕
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //发送消息给客户端
        ByteBuf byteBuf = Unpooled.copiedBuffer("Hello 客户端，我是服务器".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(byteBuf);
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //关闭通道
        ctx.close();
    }
}
